/*
 *  Everything connected to the view
 */



function IMC()
{
	// singleton
	if ( IMC.prototype._singletonInstance ) {
	      return IMC.prototype._singletonInstance;
	}
	IMC.prototype._singletonInstance = this;

	// Create Object Manager
	IM = new IM();
	
	// actual page displayed
	var page;
	// uid of the user if the page is 'user'
	var uid;
	
	/*
	 *  set page
	 *  allow the model and the controller to know on which page we are
	 */
	this.set_page = function(newPage)
	{
		page = newPage;
		IM.set_page(newPage);
		MM.set_page(newPage);
	};
	
	/*
	 *  set uid
	 */
	this.set_uid = function(newUid)
	{
		uid = newUid;
	};
	
	this.get_uid = function()
	{
		return uid;
	};
	
	/*
	 *  ask the model to display one item
	 */
	this.init_display = function(mode,id,bounds)
	{
		switch(mode)
		{
			// load object with geographical bounds
			case 'bounds' : 
				console.log('refresh all objects'); 
				// get data frIM the BDD and do the next if success
		    	IM.get('bounds', null, bounds);
		    break;
			// load only user item
			case 'user' :
				console.log('refresh all user objects');
				// get all items from one user
				IM.get('user', id, null);
			break;
			// load only one iten
			case 'item' : 
				console.log('refresh one item'); 
				IM.get('item', id, null);
			break;
		}
	};
	
	// display one item
	this.display = function(item)
	{
		if(item instanceof Item)
		{
			$('#objectBody').html(create_bigBox(item));
		}
	};
	
	// display a mini box
	this.init_miniBox = function(id)
	{
		
	};
	
	// create the mini box
	function create_miniBox(item)
	{
		var minibox;
		return miniBox;
	}
	
	// create the medium box
	function create_mediumBox(item)
	{
		
					// left element
		var left = '<a class="pull-left" href="item/'+ item.id + '">'
					+ '	<img class="pull-left img-polaroid photo-medium" src="/'+BASEPATH+'assets/uploads/'+displayPhoto(item.uid, item.imgURL)+'">'
					+ '</a>';
					// center element
		var center = '<h4 class="media-heading">' + item.title + '</h4>';
					if(page != 'm') { mediumBox += 'n comments'; }
				  	center += '<p>' + item.description + '</p>'
				  	+ '<div class="ubox'+item.uid+'">'+item.uid+'</div>';
				  	
				  	if(page != 'user')
				  	{
				  		// display miniBox in the box defined one line up, only if it's not the user page
					  	UMC.init_miniBox(item.uid, '#'+item.id + ' .ubox'+item.uid);
				  	}
				  	
				  		
				  	// right element
		var right = '<button class="btn" onclick="MM.locate(\'id\', null, null, ' + item.id + ');"><i class="icon-screenshot"></i> Locate object</button>'
				  	+ '<h3>'+displayDistance(item.distance) +' <small>away</small></h3>'
				  	+ '<h4>'+displayDate(item.added) +' <small>ago</small></h4>'
				  	if(IM.page == 'm')
				  	{
				  		// Management option available
				  		right += '<div class="object_menu">'
				  				+ '<span onClick="set_delete(' + item.id + ');" data-toggle="modal" data-target="#confirmationModal"><i class="icon-remove"></i> delete</span><br/>'
				  				+ '<span onclick="init_update('+item.id+');"><i class="icon-edit"></i> updates</span>'
				  }
		
		var mediumBox = '<div id="' + item.id + '" class="item">'
						+ left
						+ '<div class="pull-left item_content media-body" >' + center + '</div>'
						+ '<div class="pull-right">' + right + '</div>'
						+ '<div class="clearfix"></div>'
						+ '</div>';

		return mediumBox;
	}
	
	function create_bigBox(item)
	{
		$('#objectPhoto').html('<a href="#">'+displayPhotoList(item.uid, item.imgURL)+'</a>');
	
		// everything cool on the right side
		var objectRight = '<button class="btn" onclick="MM.locate(' + item.id + ');"><i class="icon-screenshot"></i> Locate object</button>'
						+ '<h3>'+displayDate(item.added) +' <small>ago</small></h3>';
		$('#objectRight').html(objectRight);
		
		var bigBox = '<h2 class="media-heading">' + item.title + '</h2>'
		'<p>' + item.description + '</p>';
	
		// display min info on the user
		'<div class="ubox'+item.uid+'">'+item.uid+'</div>';
		//UM.displayUserBox(item.uid);
	
		if(IM.page == 'm')
		{
			bigBox += '<div class="object_menu">'
			+ '<span onclick="MM.locate('+ item.id +');"><i class="icon-screenshot"></i> locate</span><br/>'
			+ '<span onClick="set_delete(' + item.id + ');" data-toggle="modal" data-target="#confirmationModal"><i class="icon-remove"></i> delete</span><br/>'
			+ '<span onclick="init_update('+item.id+');"><i class="icon-edit"></i> updates</span>'
			+ '</div>';
		}
		
		return bigBox;
		
	}

	function displayDistance(distance)
	{
		var type = 'm';
		
		if(distance >= 1000)
		{
			distance /= 1000;
			type = 'km'; 
		}
		
		distance = Math.round(distance);
		
		if(type == 'km')
		{
			distance+= ' km';
		}
		else
		{
			distance+= ' m';
		}
		
		return distance;
	};

	function displayPhotoList(uid, imgURL)
	{
		
		if(imgURL != 'empty')
		{
			// if there are images to display
			var $msg = '<img class="pull-left img-polaroid photo-medium" src="/'+BASEPATH+'assets/uploads/'+displayPhoto(uid, imgURL[0])+'">';
			$.each(imgURL, function(index, array) // create the array, index count the iterations, array is the content
			{
				$msg += '<img class="pull-left img-polaroid photo-medium" src="/'+BASEPATH+'assets/uploads/'+displayPhoto(uid, array[0])+'">';
			});
		}
		else
		{
			$msg = '<img class="pull-left img-polaroid photo-medium" src="/'+BASEPATH+'assets/uploads/'+displayPhoto(uid, 'empty')+'">';
		}
		return $msg;
	}
	
	function displayPhoto(uid, imgURL)
	{
		var array = imgURL.split(',');
		if(array[0] == 'empty')
			{
				imgURL = 'nophoto.png';
			}
		else
			{
				imgURL = uid+'/'+array[0];
			}
		return imgURL;
	};

	function displayDate(datetime)
	{
		return datetime;
	}
	
	/*
	 *  PRIVATE
	 *  Update all objects list
	 */
	this.displayList = function(items, sortBy)
	{
		//set_height('#items');
		
		if(sortBy == 'distance')
		{
			displayListByDistance(items);
		}
		if(sortBy == 'price')
		{
			displayListByPrice(items);
		}
	};
	
	function displayListByDistance(items)
	{
		sortBy = 'distance';
		var selector = '#items';
		
		console.log('selector :'+selector);
		
		var array = [];
		
		// get the map center to calculate the center
		var center = MM.get_center();
		
		/*
		for(i in items)
		{
			items[i].setDistance(center);
			array.push([items[i], items[i].distance]);
		}//*/
		
		array.sort(function(a,b) { return a[1] - b[1]; });
		//items.length = 0; // empty the array items, we cannot sort an "associative" array
		//items = [];
		
		$(selector).empty();
		
		var distCounter = 0;
		for(var i=0;i<array.length;i++)
		{
			var item = array[i][0];
			
			if(item.distance < MM.getPrecision() || page == 'user')
			{
				if(item.distance>200 && item.distance<500 && distCounter<200 && i!=0)
				{
					$(selector).append('<div class="division"><strong>- 200 m</strong></div>');
					distCounter = 200;
				}
				if(item.distance>500 && item.distance<MM.getPrecision() && distCounter<500 && i!=0)
				{
					$(selector).append('<div class="division"><strong>- 500 m</strong></div>');
					distCounter = 500;
				}
				
				// create medium Box
				var mediumBox = create_mediumBox(item, page);
				// display item
				$(selector).append(mediumBox);
			}
		}
		$(selector).append('<div class="division"><strong>- '+displayDistance(MM.getPrecision())+'</strong></div>');
		
		console.log('displayListByDistance(): success');
	};
	
	
	/*
	 *  init update
	 *  display update form
	 */
	
	this.init_update = function()
	{
		
	};
	
	/*
	 *  cancel update
	 *  hide the update form
	 */
	this.cancel_update = function()
	{
		
	};
	
	/*
	 *  update
	 *  get the update data from the form
	 */
	
	function update()
	{
		
	};
	
	/*
	 *  init delete
	 *  display delete options
	 */
	this.init_delete = function()
	{
		
	};
	
	/*
	 *  init delete
	 *  hide the delete options
	 */
	this.cancel_delete = function()
	{
		
	};
	
	/*
	 *  deleteItems (because 'delete' is a protected name)
	 *  ask the model to delete
	 */
	function deleteItems()
	{
		
	}
	
	/*
	 * init create
	 * display create form
	 */

	this.init_create = function()
	{
		console.log('init create');
		// detect click on the map
		MM.init_create();
	    document.body.style.cursor = 'crosshair';
	    $('#add_object_button').html('Cancel');
	    $("#page").hide();
	    $("#message").show();
	    $("#message").html('<div id="register_area" class="well">Choose a location on the map</div>');
	    switchInterface('map');
	    return false;
	};
	
	/*
	 *  create
	 *  get the create data from the form
	 */
	var fileCount = 0; // count the number of files uploaded
	this.create = function(manualuploader) {
		if(fileCount > '0')
		{
			manualuploader.fineUploader('uploadStoredFiles');
		}
		else
		{
			IM.create();
			IMC.cancel_create();
		}
	};
	
	this.increase_fileCount = function()
	{
		fileCount++;
	};
	
	this.decrease_fileCount = function()
	{
		fileCount--;
	};
	
	/*
	 * cancel create
	 * hide the create form
	 */
	
	this.cancel_create = function()
	{
		document.body.style.cursor = 'default';
		MM.cancel_create();
	    $('#add_object_button').html('Add an object');
	    display_alert('registration has been canceled', '#alert_area', 'error');
	    $('#page').show();
	    $('#message').hide();
	    switchInterface('content');
	    console.log('refresh');
	};
	
	/*
	 * get the string and ask the model to search
	 */
	this.init_search = function(string)
	{
		
	};
	
	/*
	 * 
	 * 
	 */
}